package com.wgt.controller;

import com.wgt.upload.baseResponse.BaseResponse;
import com.wgt.upload.bean.FileConfigBean;
import com.wgt.upload.util.Base64Util;
import com.wgt.upload.wrapper.FastDFSClientWrapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @author wgt
 * @date 2018/1/10
 * @project fastdfs-server
 */
@RestController
@RequestMapping("/file")
public class FileCliectController {

    private Logger log = LoggerFactory.getLogger(FileCliectController.class);

    @Autowired
    private FileConfigBean configBean;

    @Autowired
    private FastDFSClientWrapper clientWrapper;

    @GetMapping("/")
    public BaseResponse index(){
        log.info("####初始化页面####");
        log.info("println with file config bean :[{}]",configBean);
        return new BaseResponse("000","success");
    }

    @PostMapping("/upload")
    public BaseResponse getFileByBase64(@RequestParam("base64Code") String base64Code){
        int fileTypeStart = base64Code.indexOf("/");
        int fileTypeEnd = base64Code.indexOf(";");
        String fileType = base64Code.substring(fileTypeStart,fileTypeEnd).replace("/",".");
        log.info("file type :[{}]",fileType);

        /**
         * 截取图片数据
         */
        base64Code = base64Code.split(",")[1];
        try {
            /**
             * 保存到本地
             */
            String saveFilePath = Base64Util.getTempFileName(configBean.getFileRootPath(), fileType);

            log.info(" save file path:{}", saveFilePath);

            boolean saveSuccess = Base64Util.generateImage(base64Code, saveFilePath);
            String urlPath = clientWrapper.uploadFile(saveFilePath,fileType);
            if(saveSuccess){
                return new BaseResponse("000","success",urlPath);
            }else{
                throw new Exception("缓存图片文件时出错");
            }
        }catch (Exception e){
            log.error(e.getMessage());
            return new BaseResponse("999","未知错误");
        }
    }
}
